<?php
namespace app\lnadmin\controller;

use app\common\controller\AdminBase;
use think\facade\View;
use think\facade\Session;

use app\common\model\AuthGroupAccess;
use app\common\model\AuthRule;
use app\common\model\Admin;

class Index extends AdminBase
{
    protected $noLogin = ['login', 'captcha'];
    protected $noAuth = ['index', 'uploadImage', 'uploadFile', 'uploadVideo', 'icon', 'logout','getNavbar','delDirAndFile'];
    
    //后台首页
    public function index()
    {
        View::assign('navbar', list_to_tree($this->getNavbar()));
        $userinfo = Session::get('admin_auth');
        return View::fetch('index',['userinfo'=>$userinfo]);
    }
    //默认首页
    public function home()
    {
        $data['store'] = '11213';
        $data['monthexp'] = '3223';
        $data['exp'] = '34';
        return $this->fetch('home',['data'=>$data]);
    }
    //登陆
    public function login()
    {
        is_admin_login() && $this->redirect(url('lnadmin/index/index')); // 登录直接跳转
        if ($this->request->isPost()) {
            $param = $this->request->param();
            $result = $this->validate($param, 'login');
            if ($result !== true) {
                $this->error($result);
            }
            $admin = Admin::where([
                'username' => $param['username'],
                'password' => md5($param['password'])
            ])->find();
            if ($admin) {
                $admin['status'] != 1 && $this->error('账号已禁用');
                // 保存状态
                $auth = [
                    'admin_id' => $admin['id'],
                    'username' => $admin['username'],
                ];
                Session::set('admin_auth', $auth);
                Session::set('admin_auth_sign', data_auth_sign($auth));
                // 更新信息
                Admin::update([
                    'last_login_time' => time(),
                    'last_login_ip'   => $this->request->ip(),
                    'login_count'     => $admin['login_count'] + 1,
                ],['id' => $admin['id']]);
                insert_admin_log('登录了后台系统');
                $this->success('登录成功', url('index'));
            } else {
                $this->error('账号或密码错误');
            }
        }
        return View::fetch('login');
    }
    //修改密码
    public function editPassword()
    {
        if ($this->request->isPost()) {
            $param = $this->request->param();
            // 验证条件
            empty($param['password']) && $this->error('请输入旧密码');
            empty($param['new_password']) && $this->error('请输入新密码');
            empty($param['rep_password']) && $this->error('请输入确认密码');
            !check_password($param['new_password'], 6, 16) && $this->error('请输入6-16位的密码');
            $param['new_password'] != $param['rep_password'] && $this->error('两次密码不一致');
            $admin = Admin::where('id', session('admin_auth.admin_id'))->find();
            $admin['password'] != md5($param['password']) && $this->error('旧密码错误');
            $data = ['id' => session('admin_auth.admin_id'), 'password' => $param['new_password']];
            $result = Admin::update($data);
            if ($result == true) {
                insert_admin_log('修改了登录密码');
                session('admin_auth', null);
                session('admin_auth_sign', null);
                $this->success('更新成功', url('lnadmin/index/index'));
            } else {
                $this->error($this->errorMsg);
            }
        }
        return $this->fetch('editPassword');
    }
    // 获取导航栏
    public function getNavbar()
    {
        $where = ['type' => 'nav', 'status' => 1];
        if (Session::get('admin_auth.admin_id') != '1') {
            $access  = AuthGroupAccess::with('authGroup')->where('uid', Session::get('admin_auth.admin_id'))->find();
            //$where['id'] = ['in', $access['rules']];
            if($access){
                $where = "type='nav' and status = '1' and id in(".$access['rules'].")";
            }
        }
        $navs = AuthRule::where($where)->order('sort_order asc')->select();
        return collection($navs)->toArray();
    }
    /**
     * 刷新数据缓存
     */
    public function clear()
    {
        $root = app()->getRootPath() . 'runtime/';
        // var_dump($root);die;
        $adminRoute = $root . 'admin';
        $apiRoute = $root . 'api';
        $userRoute = $root . 'user';
        // $cacheRoute = $root . 'user';
        $cache = [];

        if(is_dir($adminRoute))
            $cache[$adminRoute] = scandir($adminRoute);
        if(is_dir($apiRoute))
            $cache[$apiRoute] = scandir($apiRoute);
        if(is_dir($userRoute))
            $cache[$userRoute] = scandir($userRoute);

        foreach ($cache as $p => $list) {
            foreach ($list as $file) {
                if (!in_array($file, ['.', '..', 'log', 'route.php'])) {
                    $path = $p . '/' . $file;
                    if (is_file($path)) {
                        @unlink($path);
                    } else {
                        $this->delDirAndFile($path);
                    }
                }
            }
        }
        return $this->success('数据缓存刷新成功!',url('lnadmin/index/home'));
    }
     /** 递归删除文件
     * @param $dirName
     * @param bool $subdir
     */
    protected function delDirAndFile($dirName)
    {
        $list = glob($dirName . '*');
        foreach ($list as $file) {
            if (is_dir($file))
                $this->delDirAndFile($file . '/');
            else
                @unlink($file);
        }
        @rmdir($dirName);
    }
    // 退出登录
    public function logout()
    {
        insert_admin_log('退出了后台系统');
        session('admin_auth', null);
        session('admin_auth_sign', null);
        return $this->redirect(url('lnadmin/index/login'));
    }
}
